<template>
    <div id="notification"></div>
</template>

<script>
import webSocketHandler from "../../utils/WebSocket";
import store from "../../store/store";
import messageTypeHandler from "../../utils/MessageTypeHandler";

export default {
    data() {
        return {
            webSocketHandler: null
        }
    },
    created() {
        let webSocketId = store.state.webSocketId
        this.webSocketHandler = webSocketHandler(webSocketId, this.onmessage, this.onopen, this.onclose)
    },
    methods: {
        onmessage(event) {
            //收到websocket消息交给MessageTypeHandler处理
            messageTypeHandler(JSON.parse(event.data));
        },
        onopen() {
            let message = store.state.user + this.greeting();
            this.$notify({
                title: '提示',
                type: 'success',
                message: message,
                showClose: false,
                duration: 2000
            });
        },
        onclose(event) {
            console.log("overwrite onclose", event);
        },
        greeting() {
            // 获取当前时间
            let timeNow = new Date();
            // 获取当前小时
            let hours = timeNow.getHours();
            // 设置默认文字
            let text = ``;
            // 判断当前时间段
            if (hours >= 0 && hours <= 10) {
                text = ` 早上好! `;
            } else if (hours > 10 && hours <= 14) {
                text = ` 中午好! `;
            } else if (hours > 14 && hours <= 18) {
                text = ` 下午好! `;
            } else if (hours > 18 && hours <= 24) {
                text = ` 晚上好! `;
            }
            // 返回当前时间段对应的状态
            return text;
        },
        closeWebSocket() {
            this.webSocketHandler.close();
        }
    }
}
</script>

